package cn.hzking.gjmall.activitys.order;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.fingdo.statelayout.StateLayout;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

import java.text.ParseException;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.hzking.gjmall.R;
import cn.hzking.gjmall.activitys.MainActivity;
import cn.hzking.gjmall.activitys.refund.ApplyRefundActivity;
import cn.hzking.gjmall.activitys.refund.RefundScheduleActivity;
import cn.hzking.gjmall.activitys.wuliu.WuliuDetailActivity;
import cn.hzking.gjmall.adpters.order.OrderDetailAdapter;
import cn.hzking.gjmall.app.Gjmall;
import cn.hzking.gjmall.base.ColorStatuBarActivity;
import cn.hzking.gjmall.bean.PayBean;
import cn.hzking.gjmall.bean.PayMessageBean;
import cn.hzking.gjmall.bean.event.OrderStateChangeBean;
import cn.hzking.gjmall.bean.order.OrderDetailBean;
import cn.hzking.gjmall.dialog.RefundTipDialog;
import cn.hzking.gjmall.net.RetrofitFactory;
import cn.hzking.gjmall.net.base.BaseEntity;
import cn.hzking.gjmall.net.base.BaseObserver;
import cn.hzking.gjmall.net.base.GjCustomStateViewObserver;
import cn.hzking.gjmall.utils.CheckInstallApp;
import cn.hzking.gjmall.utils.FormatUtil;
import cn.hzking.gjmall.utils.ListUtils;
import cn.hzking.gjmall.utils.TimeManagement;
import cn.hzking.gjmall.utils.UIUtils;
import cn.hzking.gjmall.view.SimpleOptionView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class OrderDetailActivity extends ColorStatuBarActivity implements RefundTipDialog.RefundInterface,OrderDetailAdapter.OrderRefundInterface{
    @Bind(R.id.sl) StateLayout sl;
    @Bind(R.id.srl) SwipeRefreshLayout srl;
    @Bind(R.id.simpleTileView) SimpleOptionView titleTv;
    @Bind(R.id.tv_receiver) TextView receiverTv;
    @Bind(R.id.tv_tel) TextView telTv;
    @Bind(R.id.tv_address) TextView addressTv;
    @Bind(R.id.tv_state) TextView stateTv;
    @Bind(R.id.sure_order_price) TextView orderpriceTv;
    @Bind(R.id.sure_order_suifei) TextView shuifeiTv;
    @Bind(R.id.sure_order_yunfei) TextView yunfeiTv;
    @Bind(R.id.sure_order_activity) TextView couponamountTv;
    @Bind(R.id.tv_realpay) TextView realamountTv;
    @Bind(R.id.tv_creattime) TextView creattimeTv;
    @Bind(R.id.tv_paytime) TextView paytimeTv;
    @Bind(R.id.tv_payway) TextView paywayTv;
    @Bind(R.id.tv_tradeno) TextView tradenoTv;
    @Bind(R.id.tv_wuliu) TextView wuliuTv;
    @Bind(R.id.tv_sure) TextView sureTv;
    @Bind(R.id.tv_service) TextView serviceTv;
    @Bind(R.id.tv_del) TextView delTv;
    @Bind(R.id.tv_cancel) TextView cancelTv;
    @Bind(R.id.tv_pay) TextView payTv;
    @Bind(R.id.rv) RecyclerView rv;
    private OrderDetailAdapter adapter;
    private int orderId;
    private int orderGroupId;
    private IWXAPI api;
    public static final int REFUND_CODE=100;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_order_detail);
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        if(getIntent()!=null){
            orderId=getIntent().getIntExtra("orderId",0);
            orderGroupId=getIntent().getIntExtra("orderGroupId",0);
        }
        init();
        srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData(orderId,false,true,false);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void init() {
        api = WXAPIFactory.createWXAPI(this, Gjmall.getWxAppId());

        titleTv.setTitle("订单详情");
        rv.setLayoutManager(new LinearLayoutManager(this));
        adapter=new OrderDetailAdapter(R.layout.item_orderdetail,null);
        adapter.setOrderRefundInterface(this);
        rv.setAdapter(adapter);
        initData(orderId,true,false,true);

        cancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                createDialog("您是否取消该订单?",orderId,1);
            }
        });
        delTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(OrderDetailActivity.this, ApplyRefundActivity.class);
                intent.putExtra("orderId",orderId);
                startActivity(intent);
               //createDialog("您是否删除该订单?",orderId,2);
            }
        });
        wuliuTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(OrderDetailActivity.this, WuliuDetailActivity.class);
                intent.putExtra("orderId",orderId);
                startActivity(intent);
            }
        });
        payTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                payWx(""+orderGroupId);
            }
        });
        sureTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                createDialog("您是否确认收货?",orderId,3);
            }
        });
    }


    public void createDialog(String title, final int orderId, final int type) {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_order, null);// 得到加载view
        TextView titleTv=view.findViewById(R.id.tv_title);
        TextView cancelTv=view.findViewById(R.id.tv_cancel);
        TextView sureTv=view.findViewById(R.id.tv_sure);
        titleTv.setText(title);

        final Dialog orderDialog = new Dialog(this, R.style.mydialog);// 创建自定义样式dialog
        orderDialog.setCanceledOnTouchOutside(false);
        orderDialog.setCancelable(false);
        orderDialog.setContentView(view);
        cancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                orderDialog.dismiss();
            }
        });
        sureTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                orderDialog.dismiss();
                if(type==1){
                    cancel(orderId);
                }else if(type==2){
                    del(orderId);
                }else if(type==3){
                    sure(orderId);
                }
            }
        });
        orderDialog.show();
    }

    private void sure(final int orderId) {
        RetrofitFactory.getInstant().API()
                .sureReceive(orderId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseEntity>(this,true) {
                    @Override
                    protected void onSuccees(BaseEntity baseEntity) throws Exception {
                        EventBus.getDefault().postSticky(new OrderStateChangeBean("statechange"));
                        initData(orderId,false,false,false);
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        if(isNetWorkError) {
                            UIUtils.showToast(OrderDetailActivity.this, "网络不给力", Toast.LENGTH_SHORT);
                        }else {
                            UIUtils.showToast(OrderDetailActivity.this, "服务器错误", Toast.LENGTH_SHORT);
                        }
                    }

                    @Override
                    protected void onCodeError(BaseEntity baseEntity) throws Exception {
                        super.onCodeError(baseEntity);
                        UIUtils.showToastShort(OrderDetailActivity.this,baseEntity.getErrorMsg());
                    }
                });
    }

    private void cancel(final int orderId) {//取消订单
        RetrofitFactory.getInstant().API()
                .cancelOrder(orderId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseEntity>(this,true) {
                    @Override
                    protected void onSuccees(BaseEntity baseEntity) throws Exception {
                        EventBus.getDefault().postSticky(new OrderStateChangeBean("statechange"));
                        initData(orderId,false,false,false);
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        if(isNetWorkError) {
                            UIUtils.showToast(OrderDetailActivity.this, "网络不给力", Toast.LENGTH_SHORT);
                        }else {
                            UIUtils.showToast(OrderDetailActivity.this, "服务器错误", Toast.LENGTH_SHORT);
                        }
                    }

                    @Override
                    protected void onCodeError(BaseEntity baseEntity) throws Exception {
                        super.onCodeError(baseEntity);
                        UIUtils.showToastShort(OrderDetailActivity.this,baseEntity.getErrorMsg());
                    }
                });
    }
    private void del(final int orderId) {//删除订单
        RetrofitFactory.getInstant().API()
                .deleteOrder(orderId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseEntity>(this,false) {
                    @Override
                    protected void onSuccees(BaseEntity baseEntity) throws Exception {
                        View view = View.inflate(OrderDetailActivity.this,R.layout.layout_statelayout_custom_order_empty,null);
                        TextView gobuyTv=view.findViewById(R.id.tv_gobuy);
                        gobuyTv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                EventBus.getDefault().post("goHome");
                                Intent intent = new Intent(OrderDetailActivity.this, MainActivity.class);
                                startActivity(intent);
                            }
                        });
                        sl.showCustomView(view);
                        EventBus.getDefault().postSticky(new OrderStateChangeBean("statechange"));
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        if(isNetWorkError) {
                            UIUtils.showToast(OrderDetailActivity.this, "网络不给力", Toast.LENGTH_SHORT);
                        }else {
                            UIUtils.showToast(OrderDetailActivity.this, "服务器错误", Toast.LENGTH_SHORT);
                        }
                    }

                    @Override
                    protected void onCodeError(BaseEntity baseEntity) throws Exception {
                        super.onCodeError(baseEntity);
                        UIUtils.showToastShort(OrderDetailActivity.this,baseEntity.getErrorMsg());
                    }
                });
    }

    private void payWx(String orderGroupId) {//支付
        RetrofitFactory.getInstant().API()
                .payWx(orderGroupId)
                .compose(this.<PayBean>setThread())
                .subscribe(new BaseObserver<PayBean>(this, true, true) {
                    @Override
                    protected void onSuccees(PayBean payBean) throws Exception {
                        if (payBean != null) {
                            PayBean.DataBean data = payBean.getData();
                            if (data != null) {
                                PayBean.DataBean.SignPackageBean signPackage = data.getSignPackage();
                                if (signPackage != null) {
                                    PayReq req = new PayReq();
                                    req.appId = signPackage.getAppId();
                                    req.partnerId = signPackage.getPartnerId();
                                    req.prepayId = signPackage.getPrepayid();
                                    req.packageValue = signPackage.getPackageX();
                                    req.nonceStr = signPackage.getNonceStr();
                                    req.timeStamp = signPackage.getTimeStamp();
                                    req.sign = signPackage.getPaySign();
                                    req.extData = "app data";
                                    if (CheckInstallApp.isWeixinAvilible(Gjmall.getApplicationContext())) {
                                        api.sendReq(req);
                                        UIUtils.showToast(OrderDetailActivity.this, "正在调起支付", Toast.LENGTH_SHORT);
                                    } else {
                                        UIUtils.showToast(OrderDetailActivity.this, "请安装微信", Toast.LENGTH_SHORT);
                                    }
                                }
                            }
                        }

                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {

                    }

                    @Override
                    protected void onCodeError(PayBean payBean) throws Exception {
                        super.onCodeError(payBean);
                    }
                });
    }

    private void initData(int orderId,boolean isFirst, boolean refresh,boolean isShowDialog) {
        RetrofitFactory.getInstant().API()
                .orderDetails(orderId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new GjCustomStateViewObserver<OrderDetailBean>(this,sl,srl,
                        isFirst,refresh,isShowDialog,true,null,null,null) {
                    @Override
                    protected void onBusinessSuccess(OrderDetailBean orderDetailBean) throws Exception {
                        //成功加载页面数据
                        if(orderDetailBean!=null){
                            setData(orderDetailBean);
                            srl.setEnabled(false);
                        }
                    }

                    @Override
                    protected void onChildFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        srl.setEnabled(true);
                    }

                    @Override
                    protected void onBusinessFail(OrderDetailBean orderDetailBean) {
                        super.onBusinessFail(orderDetailBean);
                        srl.setEnabled(true);
                        UIUtils.showToastShort(OrderDetailActivity.this,orderDetailBean.getErrorMsg());
                    }
                });
    }

    private void setData(OrderDetailBean orderDetailBean) {
        if(!ListUtils.isEmpty(orderDetailBean.getData().getOrderDO())){
            List<OrderDetailBean.DataBean.OrderDOBean> list=orderDetailBean.getData().getOrderDO();
            OrderDetailBean.DataBean.OrderDOBean orderDOBean=list.get(0);
            receiverTv.setText(orderDOBean.getReceiverName());
            telTv.setText(orderDOBean.getReceiverTel());
            addressTv.setText(orderDOBean.getLongAddress());
            stateTv.setText(orderDOBean.getOrderStatusStr());
            orderpriceTv.setText("订单金额: ¥"+ FormatUtil.format(orderDOBean.getTotalPrice()));
            shuifeiTv.setText("税费: ¥"+ FormatUtil.format(orderDOBean.getTaxPrice()));
            yunfeiTv.setText("运费: ¥"+ FormatUtil.format(orderDOBean.getFreight()));
            couponamountTv.setText("优惠券抵扣: ¥"+ FormatUtil.format(orderDOBean.getCouponReducePrice()));
            realamountTv.setText("实付金额: ¥"+ FormatUtil.format(orderDOBean.getOrderPrice()));
            if(orderDOBean.getStatus().equals("TRADE_CLOSED")){
                cancelTv.setVisibility(View.GONE);
                payTv.setVisibility(View.GONE);
                wuliuTv.setVisibility(View.GONE);
                serviceTv.setVisibility(View.GONE);
                sureTv.setVisibility(View.GONE);
                delTv.setVisibility(View.VISIBLE);
            }else if (orderDOBean.getStatus().equals("WAIT_BUYER_PAY")){
                cancelTv.setVisibility(View.VISIBLE);
                payTv.setVisibility(View.VISIBLE);
                wuliuTv.setVisibility(View.GONE);
                serviceTv.setVisibility(View.GONE);
                sureTv.setVisibility(View.GONE);
                delTv.setVisibility(View.GONE);
            }else if(orderDOBean.getStatus().equals("WAIT_SEND_GOODS")){
                cancelTv.setVisibility(View.GONE);
                payTv.setVisibility(View.GONE);
                wuliuTv.setVisibility(View.VISIBLE);
                if(orderDOBean.isRefund()){
                    serviceTv.setText("退款进程");
                    serviceTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent=new Intent(OrderDetailActivity.this, RefundScheduleActivity.class);
                            intent.putExtra("orderId",orderId);
                            startActivity(intent);
                        }
                    });
                }else {
                    serviceTv.setText("申请售后");
                    serviceTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            RefundTipDialog dialog=new RefundTipDialog(OrderDetailActivity.this,R.style.mydialog);
                            dialog.setRefundInterface(OrderDetailActivity.this);
                            dialog.show();
                        }
                    });
                }
                serviceTv.setVisibility(View.VISIBLE);
                sureTv.setVisibility(View.GONE);
                delTv.setVisibility(View.GONE);
            }else if(orderDOBean.getStatus().equals("ALREADY_SEND")){
                cancelTv.setVisibility(View.GONE);
                payTv.setVisibility(View.GONE);
                wuliuTv.setVisibility(View.VISIBLE);
                serviceTv.setVisibility(View.GONE);
                sureTv.setVisibility(View.VISIBLE);
                delTv.setVisibility(View.GONE);
            }else if(orderDOBean.getStatus().equals("REFUNDED_CLOSED")){
                cancelTv.setVisibility(View.GONE);
                payTv.setVisibility(View.GONE);
                wuliuTv.setVisibility(View.GONE);
                serviceTv.setVisibility(View.GONE);
                sureTv.setVisibility(View.GONE);
                delTv.setVisibility(View.VISIBLE);
            }else if(orderDOBean.getStatus().equals("TRADE_FINISHED")){
                cancelTv.setVisibility(View.GONE);
                payTv.setVisibility(View.GONE);
                wuliuTv.setVisibility(View.VISIBLE);
                serviceTv.setVisibility(View.GONE);
                sureTv.setVisibility(View.GONE);
                delTv.setVisibility(View.VISIBLE);
            }
            try {
                creattimeTv.setText("下单时间: "+ TimeManagement.getDetailDate(orderDOBean.getGmtCreate()));
                paytimeTv.setText("支付时间: "+ TimeManagement.getDetailDate(orderDOBean.getGmtPayment()));
                paywayTv.setText("支付方式: "+orderDOBean.getPaymethod());
                tradenoTv.setText("交易号: "+orderDOBean.getTransactionId());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            adapter.setNewData(list);
        }
    }

    @Override
    public void refund() {
        RetrofitFactory.getInstant().API()
                .refundOrder(orderId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseEntity>(this,false) {
                    @Override
                    protected void onSuccees(BaseEntity baseEntity) throws Exception {
                        serviceTv.setText("");
                        Intent intent=new Intent(OrderDetailActivity.this, RefundScheduleActivity.class);
                        intent.putExtra("orderId",orderId);
                        intent.putExtra("refundType","onlyRefund");
                        startActivityForResult(intent,REFUND_CODE);
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        if(isNetWorkError) {
                            UIUtils.showToast(OrderDetailActivity.this, "网络不给力", Toast.LENGTH_SHORT);
                        }else {
                            UIUtils.showToast(OrderDetailActivity.this, "服务器错误", Toast.LENGTH_SHORT);
                        }
                    }

                    @Override
                    protected void onCodeError(BaseEntity baseEntity) throws Exception {
                        super.onCodeError(baseEntity);
                        UIUtils.showToastShort(OrderDetailActivity.this,baseEntity.getErrorMsg());
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==REFUND_CODE){
            initData(orderId,false,false,false);
        }
    }

    @Override
    public void service(int orderId, int orderItemId) {
        Intent intent=new Intent(OrderDetailActivity.this,ApplyRefundActivity.class);
        intent.putExtra("orderId",orderId);
        intent.putExtra("orderItemId",orderItemId);
        startActivity(intent);
    }

    @Override
    public void serviceSchedule(int orderRefundId) {
        Intent intent=new Intent(OrderDetailActivity.this,RefundScheduleActivity.class);
        intent.putExtra("orderRefundId",orderRefundId);
        startActivity(intent);
    }
}
